module.exports = () => {
  return async (ctx, next) => {
    try {
      ctx.throw = throwExp;
      await next();
    } catch (error) {
      // 说明抛出的是业务错误
      if (error instanceof HttpException) {
        ctx.body = {
          ...error,
        };
        return;
      }
      // 其他类型的错误
      const isDev = process.env.NODE_ENV === "development";
      ctx.body = {
        code: 500,
        message: isDev ? error.message : "系统错误，请联系管理员：13811065680",
      };
    }
  };
};

class HttpException {
  constructor(code, message) {
    this.code = code;
    this.message = message;
  }
}

function throwExp(code = 500, message = "系统异常") {
  throw new HttpException(code, message);
}
